@echo off
chcp 65001 >nul
setlocal enabledelayedexpansion

:: 监控系统启动脚本 (Windows版本)
:: 用于启动fy-space项目的监控功能

:: 项目信息
set PROJECT_NAME=fy-space
set JAR_NAME=fy-space.jar
set LOG_DIR=logs
set PID_FILE=fy-space.pid

:: 颜色定义 (Windows CMD不支持ANSI颜色，使用文本标识)
set RED=[错误]
set GREEN=[成功]
set YELLOW=[警告]
set BLUE=[信息]

:: 打印带标识的消息
:print_message
set color=%~1
set message=%~2
echo %color% %message%
goto :eof

:: 检查Java环境
:check_java
java -version >nul 2>&1
if errorlevel 1 (
    call :print_message "%RED%" "错误: 未找到Java环境，请先安装Java 8或更高版本"
    exit /b 1
)

for /f "tokens=3" %%i in ('java -version 2^>^&1 ^| findstr /i "version"') do (
    set JAVA_VERSION=%%i
    set JAVA_VERSION=!JAVA_VERSION:"=!
)
call :print_message "%GREEN%" "检测到Java版本: !JAVA_VERSION!"
goto :eof

:: 检查项目文件
:check_project
if not exist "%JAR_NAME%" (
    call :print_message "%RED%" "错误: 未找到项目JAR文件: %JAR_NAME%"
    call :print_message "%YELLOW%" "请确保在项目根目录下运行此脚本"
    exit /b 1
)

:: 创建日志目录
if not exist "%LOG_DIR%" (
    mkdir "%LOG_DIR%"
    call :print_message "%GREEN%" "创建日志目录: %LOG_DIR%"
)
goto :eof

:: 检查进程是否已运行
:check_running
if exist "%PID_FILE%" (
    set /p PID=<"%PID_FILE%"
    tasklist /FI "PID eq !PID!" 2>nul | find /I "!PID!" >nul
    if not errorlevel 1 (
        call :print_message "%YELLOW%" "项目已在运行中，PID: !PID!"
        exit /b 0
    ) else (
        call :print_message "%YELLOW%" "发现无效的PID文件，正在清理..."
        del "%PID_FILE%" 2>nul
    )
)
exit /b 1

:: 启动项目
:start_project
call :print_message "%BLUE%" "正在启动 %PROJECT_NAME%..."

:: 设置JVM参数
set JVM_OPTS=-Xms512m -Xmx1024m -XX:+UseG1GC -XX:+HeapDumpOnOutOfMemoryError
set JVM_OPTS=%JVM_OPTS% -XX:HeapDumpPath=%LOG_DIR%/
set JVM_OPTS=%JVM_OPTS% -Dspring.profiles.active=prod
set JVM_OPTS=%JVM_OPTS% -Dfile.encoding=UTF-8

:: 启动应用
start /B java %JVM_OPTS% -jar %JAR_NAME% > "%LOG_DIR%\startup.log" 2>&1

:: 保存PID (Windows下使用tasklist查找)
timeout /t 3 /nobreak >nul
for /f "tokens=2" %%i in ('tasklist /FI "IMAGENAME eq java.exe" /FO CSV ^| findstr /I "java.exe"') do (
    set PID=%%i
    set PID=!PID:"=!
    echo !PID! > "%PID_FILE%"
    goto :check_startup
)

:check_startup
call :print_message "%BLUE%" "等待应用启动..."
timeout /t 5 /nobreak >nul

:: 检查启动状态
if exist "%PID_FILE%" (
    set /p PID=<"%PID_FILE%"
    tasklist /FI "PID eq !PID!" 2>nul | find /I "!PID!" >nul
    if not errorlevel 1 (
        call :print_message "%GREEN%" "✅ %PROJECT_NAME% 启动成功！"
        call :print_message "%GREEN%" "PID: !PID!"
        call :print_message "%GREEN%" "日志文件: %LOG_DIR%\startup.log"
        call :print_message "%GREEN%" "监控接口: http://localhost:8633/api/admin/dashboard"
    ) else (
        call :print_message "%RED%" "❌ %PROJECT_NAME% 启动失败！"
        call :print_message "%YELLOW%" "请查看日志文件: %LOG_DIR%\startup.log"
        del "%PID_FILE%" 2>nul
        exit /b 1
    )
) else (
    call :print_message "%RED%" "❌ %PROJECT_NAME% 启动失败！"
    exit /b 1
)
goto :eof

:: 停止项目
:stop_project
if exist "%PID_FILE%" (
    set /p PID=<"%PID_FILE%"
    tasklist /FI "PID eq !PID!" 2>nul | find /I "!PID!" >nul
    if not errorlevel 1 (
        call :print_message "%BLUE%" "正在停止 %PROJECT_NAME% (PID: !PID!)..."
        taskkill /PID !PID! /F >nul 2>&1
        
        :: 等待进程结束
        for /l %%i in (1,1,30) do (
            tasklist /FI "PID eq !PID!" 2>nul | find /I "!PID!" >nul
            if errorlevel 1 (
                call :print_message "%GREEN%" "✅ %PROJECT_NAME% 已停止"
                del "%PID_FILE%" 2>nul
                goto :eof
            )
            timeout /t 1 /nobreak >nul
        )
        
        call :print_message "%GREEN%" "✅ %PROJECT_NAME% 已强制停止"
        del "%PID_FILE%" 2>nul
    ) else (
        call :print_message "%YELLOW%" "进程未运行"
        del "%PID_FILE%" 2>nul
    )
) else (
    call :print_message "%YELLOW%" "未找到PID文件"
)
goto :eof

:: 重启项目
:restart_project
call :print_message "%BLUE%" "重启 %PROJECT_NAME%..."
call :stop_project
timeout /t 2 /nobreak >nul
call :start_project
goto :eof

:: 查看状态
:status_project
call :check_running
if not errorlevel 1 (
    set /p PID=<"%PID_FILE%"
    call :print_message "%GREEN%" "✅ %PROJECT_NAME% 正在运行"
    call :print_message "%GREEN%" "PID: !PID!"
    call :print_message "%GREEN%" "监控接口: http://localhost:8633/api/admin/dashboard"
    
    :: 显示系统资源使用情况
    call :print_message "%BLUE%" "系统资源使用情况:"
    tasklist /FI "PID eq !PID!" /FO TABLE
) else (
    call :print_message "%RED%" "❌ %PROJECT_NAME% 未运行"
)
goto :eof

:: 查看日志
:view_logs
if exist "%LOG_DIR%\startup.log" (
    call :print_message "%BLUE%" "显示启动日志 (最后50行):"
    powershell "Get-Content '%LOG_DIR%\startup.log' | Select-Object -Last 50"
) else (
    call :print_message "%YELLOW%" "未找到日志文件"
)
goto :eof

:: 监控系统状态
:monitor_status
call :check_running
if not errorlevel 1 (
    set /p PID=<"%PID_FILE%"
    call :print_message "%BLUE%" "监控系统状态..."
    
    :: 检查端口是否监听
    netstat -an | findstr ":8633 " >nul
    if not errorlevel 1 (
        call :print_message "%GREEN%" "✅ 端口8633正在监听"
    ) else (
        call :print_message "%RED%" "❌ 端口8633未监听"
    )
    
    :: 测试监控接口
    call :print_message "%BLUE%" "测试监控接口..."
    powershell -Command "try { $response = Invoke-WebRequest -Uri 'http://localhost:8633/api/admin/health' -UseBasicParsing; if ($response.StatusCode -eq 200) { Write-Host '✅ 监控接口响应正常' } else { Write-Host '❌ 监控接口响应异常 (HTTP ' $response.StatusCode ')' } } catch { Write-Host '❌ 监控接口无法访问' }" 2>nul
) else (
    call :print_message "%RED%" "❌ 应用未运行，无法监控"
)
goto :eof

:: 显示帮助信息
:show_help
echo fy-space 监控系统管理脚本 (Windows版本)
echo.
echo 用法: %0 [命令]
echo.
echo 命令:
echo   start     启动应用
echo   stop      停止应用
echo   restart   重启应用
echo   status    查看应用状态
echo   logs      查看启动日志
echo   monitor   监控系统状态
echo   help      显示此帮助信息
echo.
echo 示例:
echo   %0 start      # 启动应用
echo   %0 status     # 查看状态
echo   %0 monitor    # 监控系统
goto :eof

:: 主函数
:main
if "%1"=="start" (
    call :check_java
    if errorlevel 1 exit /b 1
    call :check_project
    if errorlevel 1 exit /b 1
    call :check_running
    if not errorlevel 1 (
        call :print_message "%YELLOW%" "应用已在运行中"
        exit /b 0
    )
    call :start_project
    goto :eof
)

if "%1"=="stop" (
    call :stop_project
    goto :eof
)

if "%1"=="restart" (
    call :check_java
    if errorlevel 1 exit /b 1
    call :check_project
    if errorlevel 1 exit /b 1
    call :restart_project
    goto :eof
)

if "%1"=="status" (
    call :status_project
    goto :eof
)

if "%1"=="logs" (
    call :view_logs
    goto :eof
)

if "%1"=="monitor" (
    call :monitor_status
    goto :eof
)

if "%1"=="help" (
    call :show_help
    goto :eof
)

if "%1"=="--help" (
    call :show_help
    goto :eof
)

if "%1"=="-h" (
    call :show_help
    goto :eof
)

if not "%1"=="" (
    call :print_message "%RED%" "未知命令: %1"
    echo.
    call :show_help
    exit /b 1
)

:: 默认显示帮助
call :show_help
goto :eof

:: 执行主函数
call :main %* 